<template>
  <div class="app-container">
    <el-form ref="dataForm" :rules="rules" :model="dataForm" status-icon label-position="left" label-width="110px"
      style="width: 600px; margin-left:50px;">
      <el-form-item :label="$t('订阅名称')" prop="name">
        <el-input v-model="dataForm.name" :required="true" />
      </el-form-item>
      <el-form-item :label="$t('订阅图片')" prop="picture" :required="true">
        <el-upload :headers="headers" :action="uploadPath" :show-file-list="false" :on-success="uploadPicUrl"
          :on-remove="handleGoodsPicRemove" class="avatar-uploader" accept=".jpg,.jpeg,.png,.gif">
          <img v-if="dataForm.picture" :src="dataForm.picture" class="avatar">
          <i v-else class="el-icon-plus avatar-uploader-icon" />
          <label v-if="dataForm.picture" class="el-upload-list__item-status-label avatar-uploader__status_label"
            @click.stop="handleGoodsPicRemove()"><i class="el-icon-delete"></i></label>
        </el-upload>
      </el-form-item>
      <el-form-item :label="$t('配送时间范围')" prop="desc">
        <el-time-select prop="distributionStartTime" v-model="dataForm.distributionStartTime" :picker-options="{
          start: '00:00',
          step: '00:15',
          end: '23:59',
          maxTime: dataForm.distributionEndTime,
        }" :required="true" :placeholder='$t("选择时间")'>
        </el-time-select>
        <el-time-select prop="distributionEndTime" v-model="dataForm.distributionEndTime" :picker-options="{
          start: '00:00',
          step: '00:15',
          end: '23:59',
          minTime: dataForm.distributionStartTime,
        }" :required="true" :placeholder='$t("选择时间")'>
        </el-time-select>
      </el-form-item>
      <el-form-item :label="$t('自动续订')" prop="autoSub">
        <el-radio v-model="dataForm.autoSub" :label="1">{{ $t('自动续订') }}</el-radio>
        <el-radio v-model="dataForm.autoSub" :label="0">{{ $t('不自动续订') }}</el-radio>
      </el-form-item>
      <el-form-item :label="$t('收货方式')" prop="transportType">
        <el-checkbox-group v-model="dataForm.transportType">
          <el-checkbox :label="1">{{ $t('自取') }}</el-checkbox>
          <el-checkbox :label="2">{{ $t('门店配送') }}</el-checkbox>
          <el-checkbox :label="3">{{ $t('物流') }}</el-checkbox>
        </el-checkbox-group>
      </el-form-item>
      <el-form-item :label="$t('订单生成规则')" prop="orderRule">
        <el-radio v-model="dataForm.orderRule" :label="1">{{ $t('系统生成') }}</el-radio>
        <el-radio v-model="dataForm.orderRule" :label="2">{{ $t('会员确认') }}</el-radio>
      </el-form-item>
      <el-form-item :label="$t('使用范围')" prop="useRange">
        <el-radio v-model="dataForm.useRange" :label="1">{{ $t('通用') }}</el-radio>
        <el-radio v-model="dataForm.useRange" :label="2">{{ $t('门店使用') }}</el-radio>
        <el-radio v-model="dataForm.useRange" :label="3">{{ $t('网店使用') }}</el-radio>
      </el-form-item>
      <el-form-item :label="$t('限制区域')">
        <el-radio-group v-model="dataForm.areaLimit">
          <el-radio-button :label="0">{{ $t('不限区域') }}</el-radio-button>
          <el-radio-button :label="1">{{ $t('限制区域') }}</el-radio-button>
        </el-radio-group>
      </el-form-item>

      <el-form-item v-show="dataForm.areaLimit == 0 ? false : true">
        <el-cascader :options="locations" :props="regionProps" v-model="dataForm.regions" :show-all-levels="false"
          collapse-tags clearable>
        </el-cascader>
      </el-form-item>

      <el-form-item :label="$t('商品信息')">
        <el-table border :data="this.dataForm.subscribeSpecifications">
          <el-table-column :label="$t('商品名')" align="center" prop="selectGoodsValue" sortable></el-table-column>
          <el-table-column :label="$t('规格')" prop="selectSpecificationValue" align="center"></el-table-column>
          <el-table-column :label="$t('计量单位')" prop="unit" align="center"></el-table-column>
          <el-table-column :label="$t('数量')" prop="number" align="center"></el-table-column>
          <el-table-column :label="$t('价格')" prop="basePrice" align="center"></el-table-column>
          <el-table-column align="center" :label="$t('Operate')" width="80" class-name="small-padding fixed-width">
            <template slot="header" slot-scope="{row}">
              {{ $t('Operate') }}
              <i class="el-icon-setting" style="color: #d35e32"></i>
            </template>
            <template slot-scope="scope">
              <el-button round type="danger" icon="el-icon-delete"
                @click="handleDelete(scope.$index)"></el-button></template>
          </el-table-column>
        </el-table>
        <el-dialog :visible.sync="attributeVisiable" :title="$t('Set_merchandise_parameter_values')">
          <el-form ref="attributeForm" :model="attributeForm" :rules="rules" status-icon label-position="left"
            label-width="100px" style="width: 400px; margin-left:50px;">
            <el-form-item :label="$t('商品名称')" prop="goodsId">
              <el-select v-model="attributeForm.goodsId" :placeholder='$t("筛选商品名称")' @change="listSpecification"
                filterable remote :remote-method="getGoodsOption">
                <el-option v-for="item in goodsOptions" :key="item.id" :label="item.label" :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item :label="$t('商品规格')" prop="specificationIds">
              <!--               specificationList-->
              <el-select v-model="attributeForm.specificationIds" :placeholder='$t("请选择")'
                @change="changeSpecification">
                <el-option v-for="item in specificationList" :key="item.key" :label="item.label" :value="item.key">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item :label="$t('计量单位')" prop="unit">
              <el-input v-model="attributeForm.unit" />
            </el-form-item>
            <el-form-item :label="$t('数量')" prop="number">
              <el-input-number v-model="attributeForm.number" style="width:200px" :min="0"
                @change="changeSpecification"></el-input-number>
            </el-form-item>
            <el-form-item :label="$t('价格')" prop="basePrice">
              <el-input v-model.number="attributeForm.basePrice" />
            </el-form-item>
          </el-form>
          <div slot="footer" class="dialog-footer">
            <el-button plain1 round icon="el-icon-error" @click="handleAttributeCancel">{{ $t('Cancel') }}</el-button>
            <el-button plain1 round icon="el-icon-success" type="primary"
              @click="handleAttributeAdd">{{ $t('Confirm') }}</el-button>
          </div>
        </el-dialog>
        <el-button class="filter-item" type="warning" plain1 icon="el-icon-circle-plus" @click="handleAttributeShow"
          v-permission="['GET /admin/p/lumiere_subscribe_add']">
          {{ $t('Add') }}
        </el-button>
      </el-form-item>

      <el-form-item :label="$t('订阅方式')" prop="ruleType">
        <el-tabs type="border-card">
          <el-tab-pane :label='$t("周")'>
            <el-switch v-model="dataForm.weekType" active-color="#13ce66" inactive-color="#ff4949">
            </el-switch>
            <el-form v-if="dataForm.weekType == true">
              <el-form-item :label='$t("配送设置")' prop="type">
                <el-radio-group v-model="dataForm.weekRule.type">
                  <el-radio :label="1">
                    {{ $t('每天配送') }}<el-input :disabled='dataForm.weekRule.type != 1'
                      v-model.number="dataForm.weekRule.daysTimes" type="number" style="width:100px"
                      oninput="if(value<=0) value= 1" min="1" max="1"></el-input> 次
                  </el-radio>
                  <br />
                  <el-radio :label="2">
                    {{ $t('每周配送') }}<el-input :disabled='dataForm.weekRule.type != 2'
                      v-model.number="dataForm.weekRule.weekTimes" type="number" style="width:100px"
                      oninput="if(value<=0 || vallue >7) value= 1" min="1" max="7"></el-input> 次
                  </el-radio>
                </el-radio-group>
              </el-form-item>
              <el-from-item :label='$t("购买金额")' prop="price">
                {{ $t('购买') }}:
                <el-input v-model.number="dataForm.weekRule.price" type="number" style="width:100px"
                  oninput="if(value<0) value= 0" min="0"></el-input> {{ $t('金额') }} or
                <el-input v-model.number="dataForm.weekRule.point" style="width:100px" oninput="if(value<0) value= 0"
                  min="0"></el-input> pts
              </el-from-item>
              <br />
              <el-from-item :label='$t("续约金额")' prop="nextSubPrice">
                {{ $t('续费') }}:
                <el-input v-model.number="dataForm.weekRule.nextSubPrice" type="number" style="width:100px"
                  oninput="if(value<0) value= 0" min="0"></el-input> {{ $t('金额') }} or
                <el-input v-model.number="dataForm.weekRule.nextSubPoint" type="number" style="width:100px"
                  oninput="if(value<0) value= 0" min="0"></el-input> pts
              </el-from-item>
            </el-form>
          </el-tab-pane>
          <el-tab-pane :label='$t("月")'>
            <el-switch v-model="dataForm.monthType" active-color="#13ce66" inactive-color="#ff4949">
            </el-switch>
            <el-form v-if="dataForm.monthType == true">
              <el-form-item :label='$t("配送设置")' prop="type">
                <el-radio-group v-model="dataForm.monthRule.type">
                  <el-radio :label="1">
                    {{ $t('每天配送') }}<el-input :disabled='dataForm.monthRule.type != 1'
                      v-model.number="dataForm.monthRule.daysTimes" type="number" style="width:100px"
                      oninput="if(value<=0) value= 1" min="1" max="1"></el-input> 次
                  </el-radio>
                  <br />
                  <el-radio :label="2">
                    {{ $t('每周配送') }}<el-input :disabled='dataForm.monthRule.type != 2'
                      v-model.number="dataForm.monthRule.weekTimes" type="number" style="width:100px"
                      oninput="if(value<=0 || value >7) value= 1" min="1" max="7"></el-input> 次
                  </el-radio>
                  <br />
                  <el-radio :label="3">
                    {{ $t('每月配送') }}<el-input :disabled='dataForm.monthRule.type != 3'
                      v-model.number="dataForm.monthRule.monthTimes" type="number" style="width:100px"
                      oninput="if(value<=0 || value >31) value= 1" min="1" max="31"></el-input> 次
                  </el-radio>
                </el-radio-group>
              </el-form-item>
              <el-from-item :label='$t("购买金额")' prop="price">
                {{ $t('购买') }}: <el-input v-model.number="dataForm.monthRule.price" type="number" style="width:100px"
                  oninput="if(value<0) value= 0" min="0"></el-input> {{ $t('金额') }} or
                <el-input v-model.number="dataForm.monthRule.point" type="number" style="width:100px"
                  oninput="if(value<0) value= 0" min="0"></el-input> pts
              </el-from-item>
              <br />
              <el-from-item :label='$t("续约金额")' prop="nextSubPrice">
                {{ $t('续费') }}: <el-input v-model.number="dataForm.monthRule.nextSubPrice" type="number"
                  style="width:100px" oninput="if(value<0) value= 0" min="0"></el-input> {{ $t('金额') }} or
                <el-input v-model.number="dataForm.monthRule.nextSubPoint" type="number" style="width:100px"
                  oninput="if(value<0) value= 0" min="0"></el-input> pts
              </el-from-item>
            </el-form>
          </el-tab-pane>
          <el-tab-pane :label='$t("年")'>
            <el-switch v-model="dataForm.yearType" active-color="#13ce66" inactive-color="#ff4949">
            </el-switch>
            <el-from v-if="dataForm.yearType == true">
              <el-form-item :label='$t("配送设置")' prop="type">
                <el-radio-group v-model="dataForm.yearRule.type">
                  <el-radio :label="1">
                    {{ $t('每天配送') }}<el-input :disabled='dataForm.yearRule.type != 1'
                      v-model.number="dataForm.yearRule.daysTimes" type="number" style="width:100px" min="0"
                      max="1"></el-input> 次
                  </el-radio>
                  <br />
                  <el-radio :label="2">
                    {{ $t('每周配送') }}<el-input :disabled='dataForm.yearRule.type != 2'
                      v-model.number="dataForm.yearRule.weekTimes" type="number" style="width:100px"
                      oninput="if(value<=0 || value >7) value= 1" min="1" max="7"></el-input> 次
                  </el-radio>
                  <br />
                  <el-radio :label="3">
                    {{ $t('每月配送') }}<el-input :disabled='dataForm.yearRule.type != 3'
                      v-model.number="dataForm.yearRule.monthTimes" type="number" style="width:100px"
                      oninput="if(value<=0 || value >31) value= 1" min="1" max="31"></el-input> 次
                  </el-radio>
                  <br />
                  <el-radio :label="4">
                    {{ $t('每年配送') }}<el-input :disabled='dataForm.yearRule.type != 4'
                      v-model.number="dataForm.yearRule.yearTimes" type="number" style="width:100px"
                      oninput="if(value<=0 || value >52) value= 1" min="1" max="52"></el-input> 次
                  </el-radio>
                </el-radio-group>
              </el-form-item>
              <el-from-item :label='$t("购买金额")'>
                {{ $t('购买') }}: <el-input v-model="dataForm.yearRule.price" style="width:100px"
                  oninput="if(value<0) value= 0" min="0"></el-input> {{ $t('元') }} or
                <el-input v-model="dataForm.yearRule.point" style="width:100px" oninput="if(value<0) value= 0"
                  min="0"></el-input> pts
              </el-from-item>
              <br />
              <el-from-item :label='$t("续约金额")'>
                {{ $t('续费') }} <el-input v-model="dataForm.yearRule.nextSubPrice" style="width:100px"
                  oninput="if(value<0) value= 0" min="0"></el-input> {{ $t('元') }} or
                <el-input v-model="dataForm.yearRule.nextSubPoint" style="width:100px" oninput="if(value<0) value= 0"
                  min="0"></el-input> pts
              </el-from-item>
            </el-from>

          </el-tab-pane>
        </el-tabs>
      </el-form-item>

      <el-form-item :label="$t('订阅说明')" prop="desc">
        <el-input type="textarea" v-model="dataForm.desc" maxlength="127" placeholder="请输入内容"></el-input>
      </el-form-item>
    </el-form>
    <div class="op-container">
      <el-button plain1 round icon="el-icon-back" @click="handleBack"
        style="margin-right: 480px">{{ $t('Back') }}</el-button>
      <el-button plain1 round icon="el-icon-success" v-if="dialogStatus == 'create' && this.status != 1" type="primary"
        @click="createData">{{ $t('Confirm') }}</el-button>
      <el-button plain1 round icon="el-icon-success" v-if="dialogStatus == 'update' && this.status != 1" type="primary"
        @click="updateData">{{ $t('Confirm') }}</el-button>
    </div>
  </div>
</template>

<script>
import { listLocationRegion } from '../../api/region'
import { goodsOption, listGoods } from '../../api/goods'
import { getToken } from '../../utils/auth'
import { uploadPath } from '../../api/storage'
import {
  listGoodsOnSale,
  getSpecificationByGoods,
  createSubscribe, listSubscribeDetail, updateSubscribe
} from '../../api/lumiereSubscribe'

export default {
  name: 'subscribeAdd',
  data() {
    const defaultTypeOptions = [
      {
        label: this.$t('电子优惠券'),
        value: 1
      }
    ]

    const defaultStatusOptions = [
      {
        label: this.$t('Normal'),
        value: 0
      },
      {
        label: this.$t('Expired'),
        value: 1
      },
      {
        label: this.$t('Merchandise_removed'),
        value: 2
      }
    ]

    const validateDiscount = (rule, value, callback) => {
      let discountType = this.dataForm.discountType
      if (discountType == 1 && !value) {
        return callback(new Error(this.$t('满减金额不能为空')));
      }

      callback();
    }

    const validateRuleType = (rule, value, callback) => {
      if (!this.dataForm.weekType && !this.dataForm.monthType && !this.dataForm.yearType) {
        return callback(new Error(this.$t('请选择订阅方式')));
      } else {
        callback()
      }
    }

    return {
      attributeVisiable: false,
      attributeForm: {
        id: undefined,
        attribute: '',
        value: '',
        goodsId: '',
        selectGoodsValue: '',
        specificationIds: [],
        selectSpecificationValue: '',
        unit: '',
        number: 1,
        basePrice: 1.0,
        subscribeId: undefined,
      },
      goodsOptions: [],
      isLevelMember: false,
      isMoneyMember: false,
      uploadPath,
      typeOptions: Object.assign({}, defaultTypeOptions),
      dataForm: {
        id: undefined,
        name: undefined,
        picture: '',
        distributionStartTime: '',
        distributionEndTime: '',
        autoSub: 0,
        transportType: [],
        orderRule: 1,
        useRange: 1,
        regions: [],
        areaLimit: 1,
        weekRule: {
          id: undefined,
          type: 1,
          daysTimes: 1,
          weekTimes: 1,
          monthTimes: 1,
          yearTimes: 1,
          price: undefined,
          point: undefined,
          nextSubPrice: undefined,
          nextSubPoint: undefined,
        },
        monthRule: {
          id: undefined,
          type: 1,
          daysTimes: 1,
          weekTimes: 1,
          monthTimes: 1,
          yearTimes: 1,
          price: undefined,
          point: undefined,
          nextSubPrice: undefined,
          nextSubPoint: undefined,
        },
        yearRule: {
          id: undefined,
          type: 1,
          daysTimes: 1,
          weekTimes: 1,
          monthTimes: 1,
          yearTimes: 1,
          price: undefined,
          point: undefined,
          nextSubPrice: undefined,
          nextSubPoint: undefined,
        },
        subscribeSpecifications: [],                         //新增订阅时暂存的规格数据
        weekType: false,
        monthType: false,
        yearType: false,
        desc: undefined
      },

      dialogFormVisible: false,
      dialogStatus: '',
      list: [],
      rules: {
        name: [{ required: true, message: this.$t('订阅名称必填'), trigger: 'blur' }],
        goodsId: [{ required: true, message: this.$t('商品名称必填'), trigger: 'blur' }],
        specificationIds: [{ required: true, message: this.$t('商品规格必填'), trigger: 'blur' }],
        unit: [{ required: true, message: this.$t('计量单位必填'), trigger: 'blur' }],
        number: [{ required: true, message: this.$t('数量必填'), trigger: 'blur' }],
        basePrice: [{ required: true, message: this.$t('价格必填'), trigger: 'blur' }],
        transportType: [{ required: true, message: this.$t('配送方式必选'), trigger: 'blur' }],
        ruleType: [
          { required: false, message: '请选择订阅方式', trigger: 'blur', validator: validateRuleType },
        ]
      },
      categories: [],
      locations: [],
      goodsList: [],
      props: { multiple: true, value: 'id', label: 'name', emitPath: false },
      regionProps: { multiple: true, value: 'id', label: 'nameEn', emitPath: false },
      options: [{
        value: 0,
        label: this.$t('每年')
      }, {
        value: 1,
        label: this.$t('每月')
      }, {
        value: 2,
        label: this.$t('每周')
      }],
      goodsOnSale: [],
      specificationList: [],
      specificationQuery: {},
      status: undefined,
    }
  },
  created() {
    this.init()
    this.getLocations()
    this.listCategory()
    this.getGoodsOption()

  },
  methods: {

    init: function () {

      if (this.$route.query.id == undefined) {

      } else {
        listSubscribeDetail({ subscribeId: this.$route.query.id }).then(response => {
          this.dataForm = response.data.data
          this.status = response.data.data.status
          if (this.dataForm.regions.length == 0) {
            this.dataForm.areaLimit = 0;
          }
          let timeRanges = response.data.data.timeRanges.split("--");

          if (timeRanges[0] == 'null' || timeRanges[0] == undefined) {
            this.$set(this.dataForm, 'distributionStartTime', '')
          } else {
            this.$set(this.dataForm, 'distributionStartTime', timeRanges[0])
          }

          if (timeRanges[1] == 'null' || timeRanges[1] == undefined) {
            this.$set(this.dataForm, 'distributionEndTime', '')
          } else {
            this.$set(this.dataForm, 'distributionEndTime', timeRanges[1])
          }

          //设置周月年规则的状态
          if (response.data.data.weekType == 1) {
            this.dataForm.weekType = true;
            this.$set(this.dataForm, 'weekType', true)
          } else {
            this.$set(this.dataForm, 'weekType', false)
          }

          if (response.data.data.monthType == 1) {
            this.$set(this.dataForm, 'monthType', true)
          } else {
            this.$set(this.dataForm, 'monthType', false)
          }

          if (response.data.data.yearType == 1) {
            this.$set(this.dataForm, 'yearType', true)
          } else {
            this.$set(this.dataForm, 'yearType', false)
          }

          if (this.dataForm.weekType == false) {
            this.dataForm.weekRule.type = 1
            this.dataForm.weekRule.daysTimes = 1
            this.dataForm.weekRule.weekTimes = 1
            this.dataForm.weekRule.monthTimes = 1
            this.dataForm.weekRule.yearTimes = 1
            this.dataForm.weekRule.price = 1
            this.dataForm.weekRule.point = 1
            this.dataForm.weekRule.nextSubPrice = 1
            this.dataForm.weekRule.nextSubPoint = 1
          }

          if (this.dataForm.monthType == false) {
            this.dataForm.monthRule.type = 1
            this.dataForm.monthRule.daysTimes = 1
            this.dataForm.monthRule.weekTimes = 1
            this.dataForm.monthRule.monthTimes = 1
            this.dataForm.monthRule.yearTimes = 1
            this.dataForm.monthRule.price = 1
            this.dataForm.monthRule.point = 1
            this.dataForm.monthRule.nextSubPrice = 1
            this.dataForm.monthRule.nextSubPoint = 1
          }

          if (this.dataForm.yearType == false) {
            this.dataForm.yearRule.type = 1
            this.dataForm.yearRule.daysTimes = 1
            this.dataForm.yearRule.weekTimes = 1
            this.dataForm.yearRule.monthTimes = 1
            this.dataForm.yearRule.yearTimes = 1
            this.dataForm.yearRule.price = 1
            this.dataForm.yearRule.point = 1
            this.dataForm.yearRule.nextSubPrice = 1
            this.dataForm.yearRule.nextSubPoint = 1
          }
        })
      }

      this.dialogStatus = this.$route.query.dialogStatus
    },
    getLocations() {
      listLocationRegion().then(response => {
        this.locations = response.data.data.list
        if (this.dataForm.regions && this.dataForm.regions.length > 0) {
          let p = [];
          this.dataForm.regions.forEach(id => {
            this.locations.forEach(region => {
              if (region.children && region.children.length > 0) {
                region.children.forEach(item => {
                  if (item.children && item.children.length > 0) {
                    item.children.forEach(sub => {
                      if (sub.id == id) {
                        let tmp = sub.id;
                        p.push(tmp)
                      }
                    })
                  }
                })
              }
            })
          })
        }
      })

    },
    getGoods() {
      this.listLoading = true
      listGoods(this.listGoodsQuery).then(response => {
        this.goodsList = response.data.data.list.map(goods => {
          return {
            label: goods.name,
            key: goods.id
          }
        })
      }).catch(() => {
        this.list = []
      })
    },
    handleBack() {
      this.$router.push({ path: '/subscribe/list' })
    },
    createData() {

      this.$refs['dataForm'].validate(valid => {
        if (valid) {
          //没有选中的配送类型的对应值为0
          this.changeTimes();

          //判断是否已经选中了订阅商品


          if (this.dataForm.subscribeSpecifications.length == 0) {
            this.$notify.error({
              title: this.$t('Failed'),
              message: this.$t('请添加可选择订阅商品')
            })
            return
          } else {
            createSubscribe(this.dataForm).then(response => {
              this.$router.push({ path: '/subscribe/list' })
            })
            this.resetForm();
          }

        }
      })


    },
    updateData() {
      this.$refs['dataForm'].validate(valid => {
        if (valid) {
          this.changeTimes();
          if (this.dataForm.subscribeSpecifications.length == 0) {
            this.$notify.error({
              title: this.$t('Failed'),
              message: this.$t('请添加可选择订阅商品')
            })
            return
          } else {
            updateSubscribe(this.dataForm).then(response => {
              this.$router.push({ path: '/subscribe/list' })
            }).catch(({ data }) => {
              this.$notify.error({
                title: this.$t('Failed'),
                message: this.$t(data.errmsg || 'Failed')
              })
            })
          }
        }
      })

    },
    uploadPicUrl: function (response) {
      this.dataForm.picture = response.data.url
    },
    handleGoodsPicRemove: function () {
      this.dataForm.picture = undefined
    },
    handleChangeType() {
      if (this.dataForm.type == 3) {
        this.dataForm.userLevel = [0]
        this.dataForm.promotionOnly = false
        this.dataForm.timeType = 1
        this.dataForm.goodsType = 0
      }
    },
    handleAttributeShow() {
      this.attributeForm = {}
      this.attributeVisiable = true
      this.getGoodsOption()
    },
    handleAttributeCancel() {
      this.$refs.attributeForm.resetFields();
      this.attributeVisiable = false
    },
    handleAttributeAdd() {
      this.$refs.attributeForm.validate((valid) => {
        if (valid) {
          for (let i = 0; i < this.goodsOptions.length; i++) {
            if (this.goodsOptions[i].id == this.attributeForm.goodsId) {
              this.attributeForm.selectGoodsValue = this.goodsOptions[i].label
            }
          }
          for (let i = 0; i < this.specificationList.length; i++) {
            if (this.specificationList[i].key == this.attributeForm.specificationIds) {
              this.attributeForm.selectSpecificationValue = this.specificationList[i].label
            }
          }
          // this.dataForm.subscribeSpecifications = []
          // //debugger
          let arr = [];
          arr.push(this.attributeForm.specificationIds);
          this.attributeForm.specificationIds = arr;
          this.dataForm.subscribeSpecifications.push(this.attributeForm)
          this.attributeVisiable = false
          // this.handleAttributeCancel();
        }
      });

      //添加订阅相关商品和规格
      // 1.如果是新增就先放在页面的数组中保存，后添加订阅的时候一起存入到数据库中
      // 2.如果是修改就直接带着subscribeId一起存入到数据库\



      // // createSubscribeSpecification
      // this.attributeVisiable = false
    },
    handleDelete(data) {
      this.$confirm(this.$t('是否') + this.$t('删除该商品') + "?", this.$t('提示'), {
        confirmButtonText: this.$t('Confirm'),
        cancelButtonText: this.$t('Cancel'),
        type: 'warning'
      }).then(() => {
        this.dataForm.subscribeSpecifications.splice(data, 1);
        // this.dataForm.subscribeSpecifications.pop(this.dataForm.subscribeSpecifications[data])
      });


    },
    listCategory() {

      listGoodsOnSale().then(response => {
        this.goodsOnSale = response.data.data.list.map(goods => {
          return {
            label: goods.name,
            key: goods.id
          }
        })
      })
    },
    listSpecification() {
      this.specificationQuery = {
        goodsId: this.attributeForm.goodsId
      }

      getSpecificationByGoods(this.specificationQuery).then(response => {
        this.specificationList = response.data.data.list.map(specification => {
          return {
            label: specification.specification,
            key: specification.id,
            price: specification.price,
          }
        })
      })

      //单位
      for (let i = 0; i < this.goodsOptions.length; i++) {
        if (this.goodsOptions[i].id == this.attributeForm.goodsId) {
          this.attributeForm.unit = this.goodsOptions[i].unit
        }
      }


    },
    changeSpecification() {
      // this.attributeForm.number = 0
      for (let i = 0; i < this.specificationList.length; i++) {
        if (this.specificationList[i].key == this.attributeForm.specificationIds) {
          // //debugger
          if (this.attributeForm.number == undefined) {
            this.attributeForm.number = 1
          }
          this.attributeForm.basePrice = this.specificationList[i].price * this.attributeForm.number
          this.attributeForm.basePrice = Math.round(this.attributeForm.basePrice * 100) / 100
        }
      }
    },
    resetForm() {
      this.dataForm = {
        id: undefined,
        name: undefined,
        picture: '',
        distributionStartTime: '',
        distributionEndTime: '',
        autoSub: 0,
        transportType: [],
        orderRule: 1,
        useRange: 1,
        regions: [],
        areaLimit: 1,
        weekRule: {
          id: undefined,
          type: 1,
          daysTimes: 0,
          weekTimes: 0,
          monthTimes: 0,
          yearTimes: 0,
          price: 0,
          point: 0,
          nextSubPrice: 0,
          nextSubPoint: 0,
        },
        monthRule: {
          id: undefined,
          type: 1,
          daysTimes: 0,
          weekTimes: 0,
          monthTimes: 0,
          yearTimes: 0,
          price: 0,
          point: 0,
          nextSubPrice: 0,
          nextSubPoint: 0,
        },
        yearRule: {
          id: undefined,
          type: 1,
          daysTimes: 0,
          weekTimes: 0,
          monthTimes: 0,
          yearTimes: 0,
          price: 0,
          point: 0,
          nextSubPrice: 0,
          nextSubPoint: 0,
        },
        subscribeSpecifications: [],                         //新增订阅时暂存的规格数据
      }
    },
    changeTimes() {
      if (this.dataForm.weekRule.type == 1) {
        this.dataForm.weekRule.weekTimes = 0;
        this.dataForm.weekRule.monthTimes = 0;
        this.dataForm.weekRule.yearTimes = 0
      } else if (this.dataForm.weekRule.type == 2) {
        this.dataForm.weekRule.daysTimes = 0
        this.dataForm.weekRule.monthTimes = 0;
        this.dataForm.weekRule.yearTimes = 0
      }

      if (this.dataForm.monthRule.type == 1) {
        this.dataForm.monthRule.weekTimes = 0;
        this.dataForm.monthRule.monthTimes = 0;
        this.dataForm.monthRule.yearTimes = 0;
      } else if (this.dataForm.monthRule.type == 2) {
        this.dataForm.monthRule.daysTimes = 0;
        this.dataForm.monthRule.monthTimes = 0;
        this.dataForm.monthRule.yearTimes = 0;
      } else if (this.dataForm.monthRule.type == 3) {
        this.dataForm.monthRule.daysTimes = 0;
        this.dataForm.monthRule.weekTimes = 0;
        this.dataForm.monthRule.yearTimes = 0;
      }

      if (this.dataForm.yearRule.type == 1) {
        this.dataForm.yearRule.weekTimes = 0;
        this.dataForm.yearRule.monthTimes = 0;
        this.dataForm.yearRule.yearTimes = 0
      } else if (this.dataForm.yearRule.type == 2) {
        this.dataForm.yearRule.daysTimes = 0;
        this.dataForm.yearRule.monthTimes = 0;
        this.dataForm.yearRule.yearTimes = 0
      } else if (this.dataForm.yearRule.type == 3) {
        this.dataForm.yearRule.daysTimes = 0;
        this.dataForm.yearRule.weekTimes = 0;
        this.dataForm.yearRule.yearTimes = 0
      } else if (this.dataForm.yearRule.type == 4) {
        this.dataForm.yearRule.daysTimes = 0;
        this.dataForm.yearRule.weekTimes = 0;
        this.dataForm.yearRule.monthTimes = 0
      }
    },
    getGoodsOption(keyword) {

      // this.listLoading = true
      goodsOption({ keyword: keyword })
        .then(response => {
          this.goodsOptions = response.data.data
        })
        .catch(() => {
          this.goodsOptions = []
        })
    },
  },
  computed: {
    headers() {
      return {
        'X-Litemall-Admin-Token': getToken()
      }
    },
  }
}
</script>

<style scoped>

</style>
